//------------------------------------------------------------------------------
#include <QtGui>
#include <QMessageBox>
#include <QSqlRecord>
#include "CChatFrm.h"
#include "CMySQL.h"
//------------------------------------------------------------------------------
CChatFrm::CChatFrm(QString name, QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags)
{
	setupUi(this);
	setObjectName(name);
	
	chatThread=CChatThread::getInstance();
	connect(chatThread, SIGNAL(addLine(QSqlQuery*,int*)), this, SLOT(onAddLine(QSqlQuery*,int*)));
	chatThread->start();
}
//------------------------------------------------------------------------------
void CChatFrm::getLastId(void)
{
	QSqlQuery *query;

	if(CMySQL::getInstance()->execQuery("SELECT MAX(id)-10 AS lastId FROM chat", &query))
	{
		if(query->next())
		{
			lastId=query->record().value("lastId").toInt();
		}
	}
	delete query;
}
//------------------------------------------------------------------------------
void CChatFrm::closeEvent(QCloseEvent *event)
{
	chatThread->stop();
}
//------------------------------------------------------------------------------
void CChatFrm::onTimeout(void)
{
	QString requete;
	QString text;
	QSqlQuery *query;

	requete="SELECT id, dateMessage, heureMessage, qui, message ";
	requete+="FROM chat ";
	requete+="WHERE id > "+QString::number(lastId)+" ";
	requete+="ORDER BY id";

	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		while(query->next())
		{
			QSqlRecord rec=query->record();
			
			text="<b>"+rec.value("qui").toString()+"#</b> "+rec.value("message").toString()+"<br>";
			
			lastId=rec.value("id").toInt();
		}
	}
	delete query;
}
//------------------------------------------------------------------------------
void CChatFrm::on_cmdEnvoyer_clicked(void)
{
	QString requete;
	
	requete="INSERT INTO chat SET dateMessage=CURDATE(), heureMessage=CURTIME(), ";
	requete+="qui=\""+CMySQL::getInstance()->getUser()+"\", ";
	requete+="message=\""+textMessage->getValue()+"\" ";
	
	textMessage->setValue("");
	CMySQL::getInstance()->execQuery(requete, true);
	onTimeout();
}
//------------------------------------------------------------------------------
void CChatFrm::onAddLine(QSqlQuery *query, int *lastId)
{
	while(query->next())
	{
		QSqlRecord rec=query->record();
		
		messages->moveCursor(QTextCursor::End); 
		messages->insertHtml("<b>"+rec.value("qui").toString()+"#</b> "+rec.value("message").toString()+"<br>");
		messages->verticalScrollBar()->setValue(messages->verticalScrollBar()->maximum());
		
		*lastId=rec.value("id").toInt();
	}
}
//------------------------------------------------------------------------------